package com.pingtai.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.ezmorph.object.DateMorpher;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;

import com.pingtai.indent.entity.UserBaseIndentType;
import com.pingtai.indent.entity.UserIndentType;

public class Utils {
	/*
	 * 获取字符串中数字
	 */
	public static List<Long> getDigit(String text) {
	    List<Long> digitList = new ArrayList<Long>();
	    String[] arr = text.split("[^\\d]+");
	    for (String str : arr) {
	        if (str.length() > 0)
	            digitList.add(Long.valueOf(str));
	    }
	    return digitList;
	}
	
	/**
	 * 解析出url参数中的键值对 如 "index.jsp?Action=del&id=123"，解析出Action:del,id:123存入map中
	 * 
	 * @param URL
	 *            url地址
	 * @return url请求参数部分
	 */
	public static  Map<String, String> URLRequest(String URL) {
		Map<String, String> mapRequest = new HashMap<String, String>();
		
		if(URL.indexOf("?")!=-1){
			URL = URL.substring(URL.indexOf("?")+1);
		}
		
		String[] arrSplit = null;

		if (URL == null) {
			return mapRequest;
		}
		// 每个键值为一组 www.2cto.com
		arrSplit = URL.split("[&]");
		for (String strSplit : arrSplit) {
			String[] arrSplitEqual = null;
			arrSplitEqual = strSplit.split("[=]");

			// 解析出键值
			if (arrSplitEqual.length > 1) {
				// 正确解析
				mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);

			} else {
				if (arrSplitEqual[0] != "") {
					// 只有参数没有值，不加入
					mapRequest.put(arrSplitEqual[0], "");
				}
			}
		}
		return mapRequest;
	}

	public static String NoString(String HTMLStr) {
		String htmlStr = HTMLStr;
		String textStr = "";
		java.util.regex.Pattern p_script;
		java.util.regex.Matcher m_script;
		java.util.regex.Pattern p_style;
		java.util.regex.Matcher m_style;
		java.util.regex.Pattern p_html;
		java.util.regex.Matcher m_html;
		try {
			String regEx_script = "<[//s]*?script[^>]*?>[//s//S]*?<[//s]*?///[//s]*?script[//s]*?>";
			String regEx_style = "<[//s]*?style[^>]*?>[//s//S]*?<[//s]*?///[//s]*?style[//s]*?>";
			String regEx_html = "<[^>]+>";
			p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
			m_script = p_script.matcher(htmlStr);
			htmlStr = m_script.replaceAll("");
			p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
			m_style = p_style.matcher(htmlStr);
			htmlStr = m_style.replaceAll("");
			p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(htmlStr);
			htmlStr = m_html.replaceAll("");
			textStr = htmlStr.replaceAll(" ", "");
			textStr = htmlStr.replaceAll("<", "<");
			textStr = htmlStr.replaceAll(">", ">");
			textStr = htmlStr.replaceAll("®", "®");
			textStr = htmlStr.replaceAll("&", "&");
		} catch (Exception e) {
			System.err.println("Html2Text: " + e.getMessage());
		}
		return textStr;
	}  
	
	public static String unicodeToString(String str) {
		Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
		Matcher matcher = pattern.matcher(str);
		char ch;
		while (matcher.find()) {
			ch = (char) Integer.parseInt(matcher.group(2), 16);
			str = str.replace(matcher.group(1), ch + "");
		}
		return str;

	}
	
	public static List menuSort(List userIndentTypeList){
		Object[] objs = insertSort(userIndentTypeList.toArray(), "asc");
		List list = new ArrayList();
		for(int i=0;i<objs.length;i++){
			list.add(objs[i]);
		}
		return list;
	}
	
	public static List menuBaseSort(List baseList){
		Object[] objs = insertSort3(baseList.toArray(), "asc");
		List list = new ArrayList();
		for(int i=0;i<objs.length;i++){
			list.add(objs[i]);
		}
		return list;
	}
	
	public static List menuSort2(List userIndentTypeList){
		Object[] objs = insertSort2(userIndentTypeList.toArray(), "asc");
		List list = new ArrayList();
		for(int i=0;i<objs.length;i++){
			list.add(objs[i]);
		}
		return list;
	}
	
	public static Object[] insertSort(Object[] data, String sortType) {
        if (sortType.equals("asc")) { // 正排序，从小排到大
            // 比较的轮数
            for (int i = 1; i < data.length; i++) {
                // 保证前i+1个数排好序
                Object temp = data[i];
                int j;
                for (j = i; j > 0 && ((UserIndentType)data[j - 1]).getSort() > ((UserIndentType)temp).getSort(); j--) {
                    data[j] = data[j - 1];
                    data[j-1] = temp;
                }
            }
        } 
        return data;
    }
	
	public static Object[] insertSort2(Object[] data, String sortType) {
        if (sortType.equals("asc")) { // 正排序，从小排到大
            // 比较的轮数
            for (int i = 1; i < data.length; i++) {
                // 保证前i+1个数排好序
                Object temp = data[i];
                int j;
                for (j = i; j > 0 && ((UserIndentType)data[j - 1]).getSort2() > ((UserIndentType)temp).getSort2(); j--) {
                    data[j] = data[j - 1];
                    data[j-1] = temp;
                }
            }
        } 
        return data;
    }
	
	public static Object[] insertSort3(Object[] data, String sortType) {
        if (sortType.equals("asc")) { // 正排序，从小排到大
            // 比较的轮数
            for (int i = 1; i < data.length; i++) {
                // 保证前i+1个数排好序
                Object temp = data[i];
                int j;
                for (j = i; j > 0 && ((UserBaseIndentType)data[j - 1]).getSort2() > ((UserBaseIndentType)temp).getSort2(); j--) {
                    data[j] = data[j - 1];
                    data[j-1] = temp;
                }
            }
        } 
        return data;
    }

	public static String replaceEnter(String str){
		if(str==null){
			str="";
		}
		str = str.replace("\r\n", "<br>");
		str = str.replace("\n\r", "<br>");
		str = str.replace("\n", "<br>");
		str = str.replace("\r", "<br>");
		return str;
	}
	
	/** 
	* 从json HASH表达式中获取一个map，该map支持嵌套功能 
	* 形如：{"id" : "johncon", "name" : "小强"} 
	* 注意commons-collections版本，必须包含org.apache.commons.collections.map.MultiKeyMap 
	* @param object 
	* @return 
	*/ 
	public static Map getMapFromJson(String jsonString) { 
			setDataFormat2JAVA(); 
	        JSONObject jsonObject = JSONObject.fromObject(jsonString); 
	        Map map = new HashMap(); 
	        for(Iterator iter = jsonObject.keys(); iter.hasNext();){ 
	            String key = (String)iter.next(); 
	            map.put(key, jsonObject.get(key)); 
	        } 
	        return map; 
	    } 
	private static void setDataFormat2JAVA(){ 
		//设定日期转换格式 
		JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[] {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss"})); 
		} 
	
	/**  
     * 将InputStream转换成某种字符编码的String  
     * @param in  
     * @param encoding  
     * @return  
     * @throws Exception  
     */  
         public static String InputStreamTOString(InputStream in,String encoding) throws Exception{  
          
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
        byte[] data = new byte[1024];  
        int count = -1;  
        while((count = in.read(data,0,1024)) != -1)  
            outStream.write(data, 0, count);  
          
        data = null;  
        return new String(outStream.toByteArray(),encoding);  
    }  
}

